<template>
    <div>
        <h1 style="text-align: center;">角色添加</h1>
        <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="角色名称">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="权限分配">
                <el-tree :props="defaultProps" show-checkbox ref="auths" :data="form.auths" accordion>
                </el-tree>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleAdd()">添加</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { authList, roleAdd } from '@/request'

export default {
    data() {
        return {
            form: {
                name: '',
                auths: []
            },
            defaultProps: {
                children: 'children',
                label: 'name'
            }
        }
    },
    methods: {
        async getAuthList() {
            let data = await authList()
            this.form.auths = data.data.authlist
        },
        async handleAdd() {
            let selectedAllAuths = this.$refs.auths.getCheckedNodes()
            let authArr = selectedAllAuths.map(item => item._id)
            // console.log(authArr);
            let selectedAllParentAuths = selectedAllAuths.map(item => item.parentId)
            // console.log(selectedAllParentAuths);
            selectedAllParentAuths.forEach(item => {
                if (item != '0') {
                    let index = authArr.indexOf(item)
                    if (index < 0) {
                        authArr.push(item)
                    }
                }
            })

            let data = await roleAdd({ name: this.form.name, auths: authArr.join(',') })
            let { msg, error_code } = data
            if (error_code === 200) {
                this.$message({
                    message: msg,
                    type: 'success',
                    onClose: () => {
                        this.$router.push('/role/list')
                    }
                });
            } else {
                this.$message({
                    message: msg,
                    type: 'error'
                });
            }
        }
    },
    created() {
        this.getAuthList()
    }
}
</script>

<style></style>
